package top.rainbowecho.common.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.HttpHeaders;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author rainbow
 * @since 2020/3/31 19:14
 */
public final class AliApiCallUtil {
    private AliApiCallUtil() {}

    private static final String ALI_AUTHORIZATION = "APPCODE a37a8efab2894d2fbca45cc89aa2bc49";
    
    public static boolean idCardVerify(String cardNo, String name) {
        ImmutableMap<String, Object> param = ImmutableMap.of("cardno", cardNo, "name", name);
        String paramStr = paramJoin(param);

        String url = "https://idcard.market.alicloudapi.com/lianzhuo/idcard?" + paramStr;
        HttpResponse response = HttpUtil.createGet(url)
                .header(HttpHeaders.AUTHORIZATION, ALI_AUTHORIZATION).execute();

        if (response.isOk()) {
            String body = response.body();
            return StringUtils.contains(body, "匹配");
        }

        return response.isOk();
    }

    /**
     * 快递查询
     *
     * @param number 快递单号
     * @param type 快递商家名称
     * @return 快递信息json字符串
     */
    public static String expressQuery(String number, String type) {
        ImmutableMap<String, Object> param = ImmutableMap.of("number", number, "type", type);
        String paramStr = paramJoin(param);

        String url = "http://jisukdcx.market.alicloudapi.com/express/query?" + paramStr;
        HttpResponse response = HttpUtil.createGet(url)
                .header(HttpHeaders.AUTHORIZATION, ALI_AUTHORIZATION).execute();

        if (response.isOk()) {
            return response.body();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 快递查询，自动根据快递单号识别快递商家
     *
     * @param number 快递单号
     * @return 快递信息json字符串
     */
    public static String expressQuery(String number) {
        return expressQuery(number, "auto");
    }

    private static String paramJoin(Map<String, Object> param) {
        if (MapUtil.isNotEmpty(param)) {
            List<String> list = new ArrayList<>();
            param.forEach((k, v) -> list.add(k + "=" + v));
            return list.stream().reduce((x, y) -> String.join("&", x, y)).orElse(StringUtils.EMPTY);
        }
        return StringUtils.EMPTY;
    }
}
